using AutoMapper;
using MediatR;
using ProduceBasicData.Api.Application.Command.Material.ProductMaterial;
using ProduceBasicData.Domain.Material;
using ProduceBasicData.ErrorCode;
using ProduceBasicData.Infrastructure.Interface;

namespace ProduceBasicData.Api.Application.Handler.Material.ProductMaterial
{
    /// <summary>
    /// 产品物料批量删除处理类
    /// </summary>
    public class DeleteRangeProductMaterialHandler : IRequestHandler<DeleteRangeProductMaterialCommand, ApiResult<int>>
    {
        private readonly IBaseRespository<ProductMaterialModel> productMaterialRepository;
        private readonly IMapper mapper;

        public DeleteRangeProductMaterialHandler(
            IBaseRespository<ProductMaterialModel> productMaterialRepository,
            IMapper mapper)
        {
            this.productMaterialRepository = productMaterialRepository;
            this.mapper = mapper;
        }

        public async Task<ApiResult<int>> Handle(DeleteRangeProductMaterialCommand request, CancellationToken cancellationToken)
        {
            var result = new ApiResult<int>();

            try
            {
                // 根据ID数组获取产品物料数据
                var productMaterials = await productMaterialRepository.GetRangeAsync(request.Ids);
                if (productMaterials.Count == 0)
                {
                    result.Code = ApiEnum.Failed;
                    result.Msg = "未找到指定的产品物料";
                    return result;
                }

                // 执行批量软删除
                foreach (var productMaterial in productMaterials)
                {
                    productMaterial.Isdel = true;
                }
                await productMaterialRepository.UpdateRange(productMaterials);

                result.Code = ApiEnum.Success;
                result.Msg = "产品物料批量删除成功";
                result.Data = productMaterials.Count;
            }
            catch (Exception ex)
            {
                result.Code = ApiEnum.Failed;
                result.Msg = $"产品物料批量删除异常：{ex.Message}";
            }

            return result;
        }
    }
}
